package com.gupao.javavip.netty.push.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.apachecommons.CommonsLog;

@CommonsLog
public class MessageDelimiterEncoder extends MessageToByteEncoder<ByteBuf> {
    public static final String DELIMITER = "#$_$#";
    public static final ByteBuf DELIMITER_BYTE_BUF = Unpooled.copiedBuffer(DELIMITER.getBytes());

    @Override
    protected void encode(ChannelHandlerContext ctx, ByteBuf obj, ByteBuf out) throws Exception {
        log.debug("添加消息尾");
        //这里必须先将结束符加到前置ByteBuf（obj对象）尾部，然后再写入后置ByteBuf（out）中
        obj.writeBytes(DELIMITER.getBytes());
        out.writeBytes(obj);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.warn("与客户端断开连接:" + cause.getMessage(), cause);
        ctx.close();
    }
}
